package com.demo.my;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.beetl.ext.jfinal.BeetlRender;

import com.alibaba.fastjson.JSON;
import com.demo.db.TemplatesDB;
import com.demo.utils.MyConstants;
import com.his.emr.print.BuildFinalPrintString;
import com.his.emr.print.HtmlDivision;
import com.his.emr.print.StoreHtmlWithGenId;
import com.his.emr.print.WhosOverPageV2;
import com.his.emr.print.entity.EleIdAndBounds;
import com.his.emr.print.utils.MyFileWriter;
import com.jfinal.core.Controller;

public class MyController extends Controller {
	
	

	/**
	 * 生成首页列表的连接
	 * 使用了beetl模板引擎
	 */
	public void index(){
		String FOLDER = "my";
		String INDEX_HTML = "myindex.html";
		String sp = File.separator;
		String w = "/";
		
		/**
		 * https://www.cnblogs.com/duoting/p/4141044.html
		 * 获取web目录的方法参考上面URL
		 */
		// HttpServletRequest cannot be resolved to a type: 需要引入servlet-api-2.5.jar
		String webpath = getRequest().getSession().getServletContext().getRealPath("");
		
		try {
			File file = new File(webpath + sp + FOLDER);
			if(file.isDirectory()){
				List<String> others = new ArrayList<String>();
				File[] allFiles = file.listFiles();
				if(null != allFiles){
					String filename = null;
					for(File item : allFiles){
						if(item.isDirectory()){
							continue;
						}
						filename = item.getName().trim();
						if( !filename.equals( INDEX_HTML ) ){
							others.add(filename);
						}
					}
				}
				setAttr("filelist", others);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		render(new BeetlRender(MyConstants.WEBAPP_GT, w + FOLDER + w + INDEX_HTML));
	}
	
	/**
	 * 保存模板
	 */
	public void saveTpl(){
		Map<String,Object> map = new HashMap<String,Object>();
		String tplName = getPara("tplName");
		String tplContents = getPara("tplContents");
		if(null == tplName || null == tplContents){
			map.put("flag", false);
			map.put("msg", "缺少必要的参数!");
		}else{
			TemplatesDB tdb = new TemplatesDB();
			boolean flag = tdb.saveTpl(tplName, tplContents);
			map.put("flag", flag);
			if(flag){
				map.put("msg", "保存成功!");
			}else{
				map.put("msg", "出现错误!");
			}
			
		}
		
		renderJson(JSON.toJSONString(map));
	}
	
	/**
	 * 拿到所有模板的名称集合
	 */
	public void fetchAllTpls(){
		TemplatesDB tdb = new TemplatesDB();
		List<String> list = tdb.getAllTplNames();
		renderJson( JSON.toJSONString(list) );
	}
	
	/**
	 * 根据模板名称查询模板内容
	 */
	public void fetchOneTplByName(){
		TemplatesDB tdb = new TemplatesDB();
		String tplName = getPara("tplName");
		renderText(tdb.getContentsByName(tplName));
	}
	
	/**
	 * 为前台传递过来的html添加上页首和页尾再发送回前台!
	 */
	public void splitHtmlForPrint(){
		code101();
//		code102();
	}
	
	private void code101(){
		try {
			getRequest().setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String htmlStr = getPara("htmlStr");
		
		StoreHtmlWithGenId storeHtmlWithGenId = new StoreHtmlWithGenId();
		String genFilepath = storeHtmlWithGenId.store(htmlStr);
		String idPrefix = storeHtmlWithGenId.getPrefix();
		
		WhosOverPageV2 whosOverPage = new WhosOverPageV2(genFilepath, idPrefix);
		whosOverPage.parse();
		
		BuildFinalPrintString bfps = new BuildFinalPrintString(whosOverPage.getSourceFilepath(), whosOverPage.getPages());
		
		String printHtmlStr = bfps.finalPrintPage();
		
		Map<String,String> map = new HashMap<String,String>();
		map.put("flag", "true");
		map.put("printHtml", printHtmlStr);
		
		getResponse().setCharacterEncoding("UTF-8");
		
		renderJson(JSON.toJSONString(map));
	}
	
	private void code102(){
		try {
			getRequest().setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String htmlStr = getPara("htmlStr");
		
		StoreHtmlWithGenId storeHtmlWithGenId = new StoreHtmlWithGenId();
		String genFilepath = storeHtmlWithGenId.store(htmlStr);
		String idPrefix = storeHtmlWithGenId.getPrefix();
		
		String headHtml = storeHtmlWithGenId.getHeadHtml();
		String wholeHtml = storeHtmlWithGenId.getWholeHtml();
		
		WhosOverPageV2 whosOverPage = new WhosOverPageV2(genFilepath, idPrefix);
		List<EleIdAndBounds> overPageList = whosOverPage.parse();
		while(overPageList.size() > 0){
			HtmlDivision htmlDivision = new HtmlDivision(overPageList.get(0), headHtml, wholeHtml);
			wholeHtml = htmlDivision.done();
			MyFileWriter mfw = new MyFileWriter();
			mfw.writeb(wholeHtml);
			mfw.close();
			genFilepath = mfw.getFilepath();
			
			whosOverPage = new WhosOverPageV2(genFilepath, idPrefix);
			overPageList = whosOverPage.parse();
		}
		
		BuildFinalPrintString bfps = new BuildFinalPrintString(whosOverPage.getSourceFilepath(), whosOverPage.getPages());
		
		String printHtmlStr = bfps.finalPrintPage();
		
		Map<String,String> map = new HashMap<String,String>();
		map.put("flag", "true");
		map.put("printHtml", printHtmlStr);
		
		getResponse().setCharacterEncoding("UTF-8");
		
		renderJson(JSON.toJSONString(map));
	}
}
